package com.hoperun.utils;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import org.springframework.util.StringUtils;
import java.text.ParseException;

/**
 * Copyright: Copyright (c) 2014 CNPCMALL <br/>
 * ClassName: CustomTimestampEditor.java
 * 
 * @Description: 该类的功能描述
 * 
 * @version: v1.0.0
 * @author: fuyu
 * @date: 2014-8-14 下午1:29:12
 * 
 *        Modification History: Date Author Version Description
 *        ---------------------------------------------------------* 2014-8-14
 *        fuyu v1.0.0 修改原因
 */

public class CustomTimestampEditor extends PropertyEditorSupport
{
	
	private final SimpleDateFormat dateFormat;
	
	private final boolean allowEmpty;
	
	private final int exactDateLength;
	
	public CustomTimestampEditor(SimpleDateFormat dateFormat, boolean allowEmpty)
	{
		this.dateFormat = dateFormat;
		this.allowEmpty = allowEmpty;
		this.exactDateLength = -1;
	}
	
	public CustomTimestampEditor(SimpleDateFormat dateFormat,
			boolean allowEmpty, int exactDateLength)
	{
		this.dateFormat = dateFormat;
		this.allowEmpty = allowEmpty;
		this.exactDateLength = exactDateLength;
	}
	
	public void setAsText(String text)
		throws IllegalArgumentException
	{
		if ((this.allowEmpty) && (!(StringUtils.hasText(text))))
		{
			setValue(null);
		}
		else
		{
			if ((text != null) && (this.exactDateLength >= 0)
					&& (text.length() != this.exactDateLength))
			{
				throw new IllegalArgumentException(
						"Could not parse date: it is not exactly"
								+ this.exactDateLength + "characters long");
			}
			try
			{
				setValue(new Timestamp(this.dateFormat.parse(text).getTime()));
			}
			catch (ParseException ex)
			{
				throw new IllegalArgumentException("Could not parse date: "
						+ ex.getMessage(), ex);
			}
		}
	}
	
	public String getAsText()
	{
		Timestamp value = (Timestamp) getValue();
		return ((value != null) ? this.dateFormat.format(value) : "");
	}
}
